package com.wyb.controller;

import com.wyb.constant.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.UUID;

@RestController
@RequestMapping("/file")
@Slf4j
public class FileUpLoadController {

//    private final String URL = "http://localhost:80";

    @Value("${upload.resource.url}")
    private String dirpath;

    @Value("${server.port}")
    private String serverPort;

    @PostMapping("/upload")
    public Result fileUpload(@RequestParam(value = "file") MultipartFile file,
                             HttpServletRequest req, HttpSession session ) throws IOException {
        //获取文件名
        String suffixName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        String filename = UUID.randomUUID() + suffixName;
        //获取文件在磁盘空间的绝对路径
        File filePath = new File(dirpath);
        if(!filePath.exists()){
            filePath.mkdirs();
        }
        //创建虚拟路径
        String simplePath = getUrl() + "images/" + filename;
        //构建文件存储路径
        String fileStorePath = dirpath + filename;
        //在磁盘空间存储文件
        file.transferTo(new File(fileStorePath));

        Map<String,String> image = new HashMap<>();
        image.put("url", simplePath);
        image.put("desc", filename);

        if(StringUtils.isEmpty(simplePath)||filename.isEmpty()){
            return Result.error("文件上传失败");
        }
        return Result.success(image, "文件上传成功");
    }

    private String getUrl(){
        Properties env = System.getProperties();
        String protocol = "http";
        if (env.getProperty("server.ssl.key-store") != null) {
            protocol = "https";
        }
//        String serverPort = env.getProperty("server.port");
        serverPort = StringUtils.isEmpty(serverPort) ? "80" : serverPort;
        String contextPath = env.getProperty("server.servlet.context-path");
        if (StringUtils.isBlank(contextPath)) {
            contextPath = "/";
        }
        String hostAddress = "localhost";
        try {
            hostAddress = InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            log.warn("The host name could not be determined, using `localhost` as fallback");
        }

        return StringUtils.join(protocol, "://", hostAddress, ":", serverPort, contextPath);
    }

}
